package models

import (
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

//报损
type ErpBadreport struct {
	Id            int64
	DepartmentId  int64
	Number        string
	BadreportUser string
	BadreportTime int64
	AuditingUser  string
	AuditingTime  int64
	ExecuteUser   string
	ExecuteTime   int64
	Auditing      int   //0待审核1待执行2已驳回3已执行4已驳回执行
	TotalGoodsNum int64 //总产品数
	Remarks       string
	IsTemp        int //临时数据1是0否
}

func (a *ErpBadreport) TableName() string {
	return ErpBadreportTableName()
}
func ErpBadreportTableName() string {
	return TableName("erp_badreport")
}

//查询
type ErpBadreporteQueryParam struct {
	BaseQueryParam
	Number       string `json:"badreport_number"`
	DepartmentId int64  `json:"depid"`
	StartDate    string `json:"start_date"`
	EndDate      string `json:"end_date"`
	Auditing     int    `json:"auditing"`
}

func ErpBadreportPageList(params *ErpBadreporteQueryParam) ([]*ErpBadreport, int64) {

	ls := make([]*ErpBadreport, 0)

	query := orm.NewOrm().QueryTable(ErpBadreportTableName())

	if len(params.Number) > 0 {
		query = query.Filter("number", params.Number)
	}
	if len(params.StartDate) > 0 {
		query = query.Filter("BadreportTime__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("BadreportTime__lte", utils.GetDateParse(params.EndDate)+68400)
	}
	if params.Auditing > 0 {
		query = query.Filter("Auditing", params.Auditing)
	}
	query = query.Filter("department_id", params.DepartmentId).Filter("is_temp", 0)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func GetErpBadreportById(id int64) (*ErpBadreport, error) {

	r := new(ErpBadreport)
	err := orm.NewOrm().QueryTable(ErpBadreportTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

//按时间段
func QueryBadreportTimeSoltSeterCount(starttime, endtime int64) int64 {
	count, _ := queryBadreportTimeSoltSeter(starttime, endtime).Count()
	return count
}

func queryBadreportTimeSoltSeter(starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(ErpBadreportTableName())

	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("BadreportTime__gte", starttime).And("BadreportTime__lte", endtime))
	query = query.SetCond(cond)

	return query
}
